//
//  YSGNurseAppointmentMapSearchViewController.swift
//  EyeVisionForPatients
//
//  Created by liuyutian on 2022/3/3.
//  Copyright © 2022 QDSG. All rights reserved.
//

import UIKit


class YSGNurseAppointmentMapSearchController: BaseViewController {

    
    var model: YSGNurseAppointmentModel?
    
    private var mapView: YSGNurseAppointmentMapView!
    
    private var viewModel : YSGNurseAppointmentMapViewModel!
    
    private var search : AMapSearchAPI!
    
    private let locationManager : AMapLocationManager =  AMapLocationManager()
    
    var models: [YSGNurseAppointmentModel] = []
    
    var mapModel : AMapTip?
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        HUDTool.hideActivity()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "选择地址"
        
        mapView = YSGNurseAppointmentMapView(frame: CGRect(x: 0, y: 0, width: screenW, height: 300))
        
        self.view.addSubview(mapView)
        requestToll()
        viewModel = YSGNurseAppointmentMapViewModel()
        viewModel.completion = {[weak self] in
            self?.tableView.reloadData()
        }
        viewModel.pushCompletion = {[weak self] distance in
            let vc = YSGNurseAppointmentInfoController()
            vc.model = self?.model!
            if self?.models.count != 3  {
                return
            }
            if distance <= 5000{
                vc.Toll = String(format: "%.0f", (self?.models[0].price?.floatValue ?? 0) * 100)
                vc.fareItemCode = self?.models[0].chargeItemCode ?? ""
            }else if distance <= 10000{
                vc.Toll = String(format: "%.0f", (self?.models[1].price?.floatValue ?? 0) * 100)
                vc.fareItemCode = self?.models[1].chargeItemCode ?? ""
            }else if distance <= 15000{
                vc.Toll = String(format: "%.0f", (self?.models[2].price?.floatValue ?? 0) * 100)
                vc.fareItemCode = self?.models[2].chargeItemCode ?? ""
            }else{
                HUDTool.show(message: "预约地点超过医院服务范围")
                return
            }
            vc.distance = self?.viewModel.distance
            vc.mapModel = self?.mapModel
            self?.navigationController?.pushViewController(vc, animated: true)
        }
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.top.equalToSuperview().offset(300)
            make.bottom.equalToSuperview()
        }
        
        

   
        locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
        
        locationManager.locationTimeout = 2

        locationManager.reGeocodeTimeout = 2
        
        locationManager.desiredAccuracy = kCLLocationAccuracyBest

        locationManager.locationTimeout = 10

        locationManager.reGeocodeTimeout = 10

        HUDTool.show(in: self.view, message: "正在获取当前位置中,请稍后", position: .bottom)
        
        HUDTool.showActivity()
        locationManager.requestLocation(withReGeocode: true, completionBlock: { [weak self] (location: CLLocation?, reGeocode: AMapLocationReGeocode?, error: Error?) in
            HUDTool.hideActivity()
            if let error = error {
                let error = error as NSError
                
                if error.code == AMapLocationErrorCode.locateFailed.rawValue {
                    //定位错误：此时location和regeocode没有返回值，不进行annotation的添加
                    NSLog("定位错误:{\(error.code) - \(error.localizedDescription)};")
                    return
                }
                else if error.code == AMapLocationErrorCode.reGeocodeFailed.rawValue
                    || error.code == AMapLocationErrorCode.timeOut.rawValue
                    || error.code == AMapLocationErrorCode.cannotFindHost.rawValue
                    || error.code == AMapLocationErrorCode.badURL.rawValue
                    || error.code == AMapLocationErrorCode.notConnectedToInternet.rawValue
                    || error.code == AMapLocationErrorCode.cannotConnectToHost.rawValue {
                    
                    //逆地理错误：在带逆地理的单次定位中，逆地理过程可能发生错误，此时location有返回值，regeocode无返回值，进行annotation的添加
                    NSLog("逆地理错误:{\(error.code) - \(error.localizedDescription)};")
                }else {
                    //没有错误：location有返回值，regeocode是否有返回值取决于是否进行逆地理操作，进行annotation的添加
                }
            }
            
            if let location = location {
                NSLog("location:%@", location)
            }
            
            if let reGeocode = reGeocode {
                let tipModel = AMapTip()
                tipModel.name = reGeocode.poiName
                tipModel.address = reGeocode.formattedAddress
                tipModel.location = AMapGeoPoint.location(withLatitude: CGFloat(location?.coordinate.latitude ?? 0), longitude: CGFloat(location?.coordinate.longitude ?? 0))
                NSLog("reGeocode:%@", reGeocode)
                self?.viewModel.tableData.removeAll()
                self?.viewModel.tableData.append(tipModel)
                self?.tableView.reloadData()
            }
        })



    }

    func requestToll() {
        YSGNurseAppointmentViewModel.getProjectList("3") {[weak self] models, errorMsg, code in
            switch code {
            case .failure:
                HUDTool.showError(message: errorMsg)
            case .success:
                self?.models = models
            }
        }
    }

    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.backgroundColor = .background
        tableView.tableHeaderView = topView
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .singleLine
        tableView.delegate = self
        tableView.dataSource = self
        
        tableView.register(YSGNurseAppointmentAddressCell.nibForCell(), forCellReuseIdentifier: YSGNurseAppointmentAddressCell.reuseIdentifier())
        

        
        return tableView
    }()
    
    private lazy var topView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: screenW, height: 41))
        view.backgroundColor = .clear
        
        let textFiled = UITextField(frame: CGRect(x: 20, y: 10, width: screenW-40, height: 21))
        
        view.addSubview(textFiled)
        textFiled.leftViewMode = .always
        
        let imageSubview = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 21))
        
        let imageView = UIImageView(frame: CGRect(x: 10, y: 0, width: 30, height: 21))
        
        imageSubview.addSubview(imageView)
        
        imageView.image = UIImage(named: "search")
        imageView.contentMode = .center
        
        textFiled.leftView = imageSubview
        textFiled.placeholder = "请搜索要预约的地址,点击列表完成"
        textFiled.layer.cornerRadius = 15
        textFiled.backgroundColor = UIColor.white
        textFiled.font = UIFont.systemFont(ofSize: 11)
        textFiled.textColor = UIColor.textGray
        textFiled.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
        return view
    }()
    @objc func textFieldDidChange(_ textField: UITextField) {
        viewModel.searchTip(withKeyword: textField.text)
    }
}


//extension YSGNurseAppointmentMapSearchController:UITextFieldDelegate
//{
//    func textFieldDidChangeSelection(_ textField: UITextField) {
//        viewModel.searchTip(withKeyword: textField.text)
//    }
//
//
//}

extension YSGNurseAppointmentMapSearchController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (viewModel.tableData.count >= 5 ? 5 : viewModel.tableData.count)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: YSGNurseAppointmentAddressCell.reuseIdentifier(),
                                                 for: indexPath) as! YSGNurseAppointmentAddressCell
        cell.titleLabel.attributedText = NSMutableAttributedString(
            string: viewModel.tableData[indexPath.row].name,
            attributes: [NSAttributedString.Key.font:
                            UIFont(name: "PingFangSC-Semibold", size: 14.0)!,NSAttributedString.Key.foregroundColor:UIColor.mainColor])
        
        cell.subTitleLabel.text = viewModel.tableData[indexPath.row].address
        cell.selectionStyle = .none;
        return cell
    }
}

extension YSGNurseAppointmentMapSearchController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 65
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        mapModel = viewModel.tableData[indexPath.row]
        viewModel.searchAMapDistanceSearch(viewModel.tableData[indexPath.row].location)
    }
}


